package com.xujiu.caigoumall.config;

import cn.hutool.core.lang.Console;
import cn.hutool.cron.CronUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.wxpay.sdk.WXPay;
import com.xujiu.caigoumall.system.entity.vo.OrdersVO;
import com.xujiu.caigoumall.system.mapper.OrdersMapper;
import com.xujiu.caigoumall.system.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class OrderTimeoutCheck {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrdersService ordersService;

    private WXPay wxPay = new WXPay(new MyPayConfig());

    @Scheduled(cron = "*/50 * * * * *")
    public void checkAndCloseOrder() {
        System.out.println("订单超时自动取消！");
        try {
            //1.查询超过30min订单状态依然为待支付状态的订单
            Date time = new Date(System.currentTimeMillis() - 30 * 60 * 1000);
            QueryWrapper<OrdersVO> wrapper = new QueryWrapper<>();
            wrapper.eq("status", 1).lt("create_time",time);
            List<OrdersVO> ordersVOS = ordersMapper.selectList(wrapper);

            //2.访问微信平台接口，确认当前订单最终的支付状态
            for (OrdersVO ordersVO : ordersVOS) {
                HashMap<String, String> params = new HashMap<>();
                params.put("out_trade_no", ordersVO.getOrderId());

                Map<String, String> resp = wxPay.orderQuery(params);

                if ("SUCCESS".equalsIgnoreCase(resp.get("trade_state"))) {
                    //2.1 如果订单已经支付，则修改订单状态为"代发货/已支付"  status = 2
                    OrdersVO order = ordersMapper.selectById(ordersVO.getOrderId());
                    order.setStatus("2");
                    ordersMapper.updateById(order);
                    System.out.println("支付完成的订单关闭支付链接!");
                } else if ("NOTPAY".equalsIgnoreCase(resp.get("trade_state"))) {
                    //2.2 如果确实未支付 则取消订单：
                    //a.向微信支付平台发送请求，关闭当前订单的支付链接
                    Map<String, String> map = wxPay.closeOrder(params);
                    //b.关闭订单 恢复库存
                    ordersService.closeOrder(ordersVO.getOrderId());
                    System.out.println("超时未支付订单关闭支付链接!");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
